import axios from 'axios';
import qs from "qs";
import { useStore } from '@/store';
import { requestTimeout, requestBaseURL } from './config';
import { ErrorCodeKey, getErrorCode, openErrorMessage } from './utils';

const request = axios.create({
  timeout: requestTimeout,
  baseURL: requestBaseURL,
  withCredentials: true,
  validateStatus: (status) => {
    return status >= 200 && status <= 500; // 全部允许, 不会遇到错误就停止
  },
})

request.interceptors.request.use((config) => {
  const store = useStore()
  const isToken = (config.headers || {}).isToken === false;
  const accessToken = store.state.user.userToken?.access_token;
  // console.log(isToken, store.state.user.userToken?.access_token);
  if (accessToken && !isToken) {
    config.headers["Authorization"] = "Bearer " + accessToken; // token
  }
  if (config.method === "get") {
    config.paramsSerializer = function (params) {
      return qs.stringify(params, { arrayFormat: "brackets" });
    };
  }
  return config
}, error => {
  return Promise.reject(error);
})

request.interceptors.response.use((res) => {
  const status = (String(res.status) || "200") as ErrorCodeKey;
  const message = getErrorCode(status, res.data.message);
  if (status === "401") {
    openErrorMessage(message);
    // store.dispatch("clearUserInfo").then(() => {
    //   router.push({ path: "/login" });
    // });
    return;
  } else if (/4\d\d/.test(status)) {
    openErrorMessage(message);
    return res.data;
  } else {
    if (res.data.code === 4001) {
      openErrorMessage(message);
      return;
    } else if (res.data.code === 1) {
      openErrorMessage(message);
    }
    return res.data;
  }
}, error => {
  // 处理其他异常
  return Promise.reject(new Error(error));
})

export default request